module.exports = function(schemas){
	var passport = require('passport');
	var LocalStrategy = require('passport-local').Strategy;
	var users = schemas.user;
	var _ = require('underscore');
		
	//TODO: Not really a todo, more of a heads up
	//The httpentity model in android has a bug with
	//setting post data in the body while a session
	//cookie is attached. I added a few things to this
	//function to look in the headers instead of the body.
	//also two lines in node_modules/passport/passport_local/lib/strategy.js were changed
	
	passport.use(new LocalStrategy({
			passReqToCallback: true,
		    usernameField: 'email',
		    passwordField: 'service'
	    }, function(req, email, service, done){
	    	
	    	var header = JSON.parse(req.headers.json);
	    	
			if(!email || !service){
				if (req.session.passport.user === undefined){
					res.status(401).json({status: 'not logged in'});
		
					return done(null, false);
				} else {
					return done(null, req.session.passport.user);
				}
			} else {
				users.findOne({email: email, service: service})
				.exec(function(err, user){ 
					if(err){
						res.json({status: 'error', message: 'database access error'});
						return null;
					} else if(user && user.email){
						if(header["location"]){
							user.userLocation = header["location"];
						}
					
						if(!user.gender && header["gender"]){
							user.gender = header["gender"];
						}
					
						if(!user.birthday && header["birthday"]){
							user.birthday = new Date(header["birthday"]).getTime();
						}
						
						//Check for empty and undefined strings
						if(header["picture"] && 0 != header["picture"].length){
							user.picture = header["picture"];
						}
						
						users.find()
						.sort({points : -1})
						.exec(function(err, users){
							_.each(users, function(userFound, idx){
								//console.log(userFound.email + ' : ' + userFound.points);
								if(userFound.email === user.email){
									user.rank = idx + 1;
									user.save();
									
									return done(null, user); 
								}
							});
						});
					} else {
						return done(null, false);
					}
				});
			}
		}
	));

	passport.serializeUser(function(user, done){
		done(null, user.email);
	});

	passport.deserializeUser(function(email, done){
		done(null, {email: email});
	});
	
	return passport;
}	
	
